import { Button, Card, Divider, Form, Icon, Input, Modal, Table, message, Pagination } from "antd";
import React from "react";
import { connect } from 'dva';
import styles from "./index.less"
import moment from "moment";
import AddLanguageModel from "./addEmbeddingModel";
import UsingModelList from "./usingModelList";
import { embeddingModelList, embeddingModelDel, embeddingModelTestChange, embeddingModelChange, embeddingModelDisabled } from "@/services/embeddingModel";
import UserSession from "@/UserSession";
import { formatMessage } from 'umi-plugin-react/locale';

class LanguageModel extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      list: []
    }
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    const { form: { getFieldsValue }, currentUser } = this.props;
    const { current, size } = this.state;
    this.setState({ loading: true }, async () => {
      let obj = { current, size, name: getFieldsValue().search, urlPrefix: currentUser.tenantId == "1" ? "admin" : undefined }
      const res = await embeddingModelList(obj)
      this.setState({
        loading: false,
        list: res.records,
        total: res.total
      })
    })
  }

  doSearch = (current, size) => {
    this.setState({ current, size }, () => {
      this.getList()
    })
  }

  openModal = () => {
    this.AddLanguageModel.initModal()
  }

  toEditPage = (row) => {
    const { history } = this.props;
    const currentUser = UserSession.getCurrentUser()
    history.push({
      pathname: currentUser.tenantId != '1' ? "/embeddingModel/edit/" + row.id : "/llmCenter/embeddingModel/edit/" + row.id,
      query: { isSys: row.isSys },
    });
  }

  openUseModel = (id) => {
    this.UsingModelList.initModal(id)
  }

  doTest = async row => {
    const res = await embeddingModelTestChange({ id: row.id })
    message.info(res.message)
    this.getList()
  }

  renderRowClass = (record, index) => {
    if (record.type == 0) {
      return "defaultRowClass"
    }
  }

  removeConfirm = id => {
    Modal.confirm({
      title: formatMessage({ id: 'confirm.deleteTitle' }),
      content: formatMessage({ id: 'confirm.deleteContent' }),
      okText: formatMessage({ id: 'button.confirm' }),
      okType: "danger",
      cancelText: formatMessage({ id: 'button.cancel' }),
      onOk: () => {
        this.doRemove(id)
      }
    })
  }

  doRemove = async id => {
    const res = await embeddingModelDel({ id })
    if (res.code == -1) { } else {
      message.info(res.message)
      this.getList();
    }
  }

  switchModal = async id => {
    const res = await embeddingModelChange({ id })
    if (res.code == -1) { } else {
      message.info(res.message)
      this.getList();
    }
  }

  disabledEmbedding = async (id, disabled) => {
    const res = await embeddingModelDisabled({ id, disabled });
    console.log(res);
    if (res.code === 0) {
      message.success(formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.operationSuccess' }))
      this.getList()
    }
  }

  render() {
    const { form: { getFieldDecorator }, currentUser } = this.props;
    const { current, size, total, list, loading } = this.state;
    const columns = [
      {
        title: formatMessage({ id: 'table.modelName' }),
        dataIndex: "name",
        width: 200
      },
      {
        title: formatMessage({ id: 'table.createTime' }),
        dataIndex: "createTime",
        width: 200,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
    ];
    if (currentUser.tenantId != '1') {
      columns.push(
        {
          title: formatMessage({ id: 'table.modelOwner' }),
          dataIndex: "isSys",
          width: 200,
          render: text => {
            if (text) {
              return formatMessage({ id: 'table.systemAllocated' });
            } else {
              return formatMessage({ id: 'table.selfBuilt' });
            }
          }
        },
      )
    };
    columns.push(
      {
        title: formatMessage({ id: 'table.description' }),
        dataIndex: "description",
        width: 300
      },
      {
        title: formatMessage({ id: 'table.testStatus' }),
        dataIndex: "status",
        width: 150,
        render: (status, row) => {
          let text = '';
          switch (status) {
            case 0:
              text = formatMessage({ id: 'test.status.untested' });
              break;
            case 1:
              text = formatMessage({ id: 'test.status.passed' });
              break;
            case 2:
              text = formatMessage({ id: 'test.status.failed' });
              break;
          };

          return (
            <div>
              <Icon type="sync" style={{ marginRight: 10, cursor: "pointer" }} onClick={() => this.doTest(row)} />
              <span style={{ color: status == 1 ? '' : 'red' }}>{text}</span>
            </div>
          )
        }
      },      
    );
    if (currentUser.tenantId != '1') {
      columns.push(
        {
          title: formatMessage({ id: 'table.usageStatus' }),
          dataIndex: "used",
          width: 150,
          align: 'center',
          render: (used, row) => {
            return used ? (
              <span className="zdyButtonG">
                <Button type="primary" size="small">{formatMessage({ id: 'table.inUse' })}</Button>
              </span>
            ) : (
              <span className="zdyButtonB">
                <Button type="primary" size="small" onClick={() => this.switchModal(row.id)}>{formatMessage({ id: 'button.switch' })}</Button>
              </span>
            )
          }
        },
      )
    };
    columns.push(
      {
        title: formatMessage({ id: 'table.action' }),
        width: 200,
        fixed: "right",
        render: (text, row) => {
          return (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '16px' }}>
              {row.isSys ? (
                <span style={{ color: '#3E5BFF',cursor:"pointer" }} onClick={() => this.toEditPage(row)}>{formatMessage({ id: 'button.view' })}</span>
              ) : (
                <span style={{ color: '#3E5BFF',cursor:"pointer" }} onClick={() => this.toEditPage(row)}>{formatMessage({ id: 'button.edit' })}</span>
              )}
              {row.type == 0 || row.isSys ? '' : (
                <span style={{ color: '#D54941',cursor:"pointer" }} onClick={() => this.removeConfirm(row.id)}>{formatMessage({ id: 'button.delete' })}</span>
              )}
              {currentUser.tenantId == '1' ? (
                <>
                  {row.disabled ? <span style={{ color: '#3E5BFF',cursor:"pointer" }} onClick={() => this.disabledEmbedding(row.id, false)}>{formatMessage({ id: 'button.enable' })}</span> : null}
                  {!row.disabled ? <span style={{ color: '#faad14',cursor:"pointer" }} onClick={() => this.disabledEmbedding(row.id, true)}>{formatMessage({ id: 'button.disable' })}</span> : null}
                </>
              ) : null}
            </span>
          )
        }
      }
    )

    return (
      <Card bordered={false} style={{ height: '100%' }} bodyStyle={{ paddingBottom: 16 }}>
        <div className={styles.top}>
          <div>
            <Form layout="inline">
              <Form.Item>
                {getFieldDecorator("search")(<Input placeholder={formatMessage({ id: 'form.placeholder.enterModelName' })} />)}
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={() => this.doSearch(1, size)}>{formatMessage({ id: 'button.search' })}</Button>
              </Form.Item>
            </Form>
          </div>
          <Button type="primary" onClick={this.openModal}>{formatMessage({ id: 'button.add' })}</Button>
        </div>

        <Table
          columns={columns}
          dataSource={list}
          loading={loading}
          scroll={{ x: "auto" }}
          rowKey={'id'}
          rowClassName={this.renderRowClass}
          pagination={false}
        />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            onChange={this.doSearch}
            current={current}
            pageSize={10}
            total={total}
            showQuickJumper={true} locale={{ jump_to: formatMessage({ id: 'goTo' }) }}
          />
        ) : null}

        <AddLanguageModel onRef={ref => this.AddLanguageModel = ref} refreshParent={() => this.doSearch(current, size)} />
        <UsingModelList onRef={ref => this.UsingModelList = ref} />
      </Card>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(LanguageModel))